//
//  HomeViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 BlueSky. All rights reserved.
//


#import <AVOSCloud/AVOSCloud.h>
#import "BSKHomeViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKUserCenterViewController.h"
#import "BSKLoginViewController.h"
#import "BSKNoteTableViewCell.h"
#import "BSKTheme.h"
#import "BSKHomeVCToLoginVCanimation.h"
#import "BSKClassifyManageViewController.h"
#import "BSKconsts.h"
#import "BSKNoteViewController.h"
#import "BSKNoteType.h"
#import <UIImageView+WebCache.h>
#import "UIViewController+BSKToast.h"
#import "BSKNote.h"
#import "BSKClassifySettingViewController.h"
#import "BSKAddButtonAnimation.h"
#import "BSKMapViewController.h"
#import "BSKTypePasswdAlertView.h"
#import "BSKMenuAlertView.h"
#import "BSKTypeSelecter.h"
#import "BSKBookModeViewController.h"
#import "AFNetworking.h"
#import "BSKSyncManager.h"

#define SCROOL_L [UIScreen mainScreen].bounds.size.width
#define SCROOL_H [UIScreen mainScreen].bounds.size.height
@interface BSKHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UITextFieldDelegate>

@property(nonatomic,strong) UIImageView * titleImageView;
@property(nonatomic,strong) UIImageView * headImageView;
@property(nonatomic,strong) UIVisualEffectView * titleView;
@property(nonatomic,strong) UILabel * catgorayLabel;

@property(nonatomic,strong) UIImageView * menuHeadImageView;
@property(nonatomic,strong) UILabel * usernameLabel;
@property(nonatomic,strong) UIButton * refreshButton;
@property(nonatomic,strong) UIButton * bookModeButton;
@property(nonatomic,strong) UITableView * categoryTableView;//分类列表，tag为10086
@property(nonatomic,strong) UIView * mapModeButtonView;

@property(nonatomic,strong) UIView * menuView;//侧滑视图菜单
@property(nonatomic,strong) UITableView * notetableView;//日记列表,tag为10010
@property(nonatomic,strong) UIView * lineView;
@property(nonatomic,strong) UIVisualEffectView * coverView;//用于遮挡titleImageView
@property(nonatomic,strong) UIView * contentView;
@property(nonatomic,strong) UIView * tableHeaderView;
@property(nonatomic,strong) UITextField * searchTextField;
@property(nonatomic,assign) BOOL  menuIsOpen;
@property(nonatomic,assign) BOOL showCellAnimation;
@property(nonatomic,strong) BSKDBManager * magager;//数据库管理对象

@property(nonatomic,strong) BSKNoteType * curenttype;
@property(nonatomic,strong) BSKNoteType * cu;
@property(nonatomic,strong) NSArray * typeList;
@property(nonatomic,strong) CAGradientLayer * gradientLayer;
@property(nonatomic,strong) NSMutableArray * noteList;

@property(nonatomic, strong)UIImageView * helpImageView; // 帮助
@property(nonatomic, strong)UIButton * okButton;

//@property(nonatomic, strong)UIScrollView *scrollView; // 引导页
//@property(nonatomic, strong)UIPageControl *pageControl;
@end

@implementation BSKHomeViewController

- (void)viewDidLoad {
    _menuIsOpen = NO;
    _curenttype = [[BSKNoteType alloc]init];
    _magager = [[BSKDBManager alloc]init];
    [_magager openDataBase:@"notedatabase.db"];
    
    [self initializeUserinterFace];
    [self initializeAction];
    [self initializeData];
    if (_typeList.count>0) {
        BSKNoteType * firstType = [_typeList firstObject];
        [self ChangeCurentType:firstType];
    }
    [self setUserInterFaceWithUpdateHeaderOrNot:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noteListDataBaseDidChange) name:BSKNoteChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeListDataBaseDidChange) name:BSKtypeListChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userStatusDidChange:) name:BSKuserStatusChangeNotification object:nil];
	AVUser * user = [AVUser currentUser];
	if (user) {
		NSString * wifiOnly = [user objectForKey:@"wifiChoice"];
		NSString * autoSync = [user objectForKey:@"autoChoice"];
		if ([autoSync isEqualToString:@"yes"]) {
			if ([wifiOnly isEqualToString:@"yes"]) {
				AFNetworkReachabilityManager *rManger = [AFNetworkReachabilityManager sharedManager];
				[rManger startMonitoring];
				[rManger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
					if (status == 2) {
						[[BSKSyncManager shareSyncManager]startSyncWithController:self.navigationController];
					}
				}];
			}else{
				[[BSKSyncManager shareSyncManager]startSyncWithController:self.navigationController];
			}
		}
		
	}
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BSKNoteChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BSKtypeListChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BSKuserStatusChangeNotification object:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [self closeMenuAction:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    _showCellAnimation = YES;
    self.navigationController.delegate = self;
    
}

#pragma mark 接收更新数据的通知

-(void)noteListDataBaseDidChange{
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    [self initializeNotlistDataWithcondition:[NSString stringWithFormat:@"typeID = '%@' and userID = '%@' and noteFileName != 'null' ",_curenttype.typeID ,userId]];
    [_notetableView reloadData];
}
-(void)typeListDataBaseDidChange{
    
    [self initializeTypelistData];
    BOOL curenttypeIsDelete = YES;
    for (BSKNoteType * type in _typeList) {
        if ([type.typeID isEqualToString:_curenttype.typeID]) {
            _curenttype = type;
            curenttypeIsDelete = NO;
            break;
        }
    }
    if (curenttypeIsDelete) {
        _curenttype = [[BSKNoteType alloc]init];
        [self ChangeCurentType:[_typeList firstObject]];
    }
    [self loadContent];
    
}
-(void)userStatusDidChange:(NSNotification *)notify{
    UIImage * head = notify.object;
    if (head){
        _headImageView.image = head;
        _menuHeadImageView.image = head;
    }
    [self initializeData];
    
    [self setUserInterFaceWithUpdateHeaderOrNot:!head];
    
}
#pragma mark 初始化

-(void)initializeData{
    [self initializeTypelistData];
    [self loadContent];
}

-(void)initializeTypelistData{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"initialized"]){
        [[NSUserDefaults standardUserDefaults]  setBool:YES forKey:@"initialized"];
        [_magager creatTable:@"note" Columnns:@[
                                                @[@"noteID",		@"TEXT"],
                                                @[@"objectID",	@"TEXT"],//表示当前的日记是否已经同步
                                                @[@"isChange",	@"BOOLEAN"],//表示当前日记是否已经更改
                                                @[@"updateTime",	@"DATE"],//上次修改时间
                                                @[@"userID",		@"TEXT"],
                                                @[@"typeID",		@"TEXT"],
                                                @[@"title",		@"TEXT"],
                                                @[@"latitude",	@"DOUBLE"],//经度
                                                @[@"longitude",	@"DOUBLE"],//纬度
                                                @[@"weatherType",	@"INT"],
                                                @[@"date",		@"TEXT"],
                                                @[@"address",		@"TEXT"],
                                                @[@"subcontent",	@"TEXT"],
                                                @[@"noteFileName",@"TEXT"],
                                                ]];
        [_magager creatTable:@"type" Columnns:@[
                                                @[@"objectID",		@"TEXT"],//表示当前的日记是否已经同步,null表示未同步，有值表示已同步
                                                @[@"typeID",		@"TEXT"],
                                                @[@"userID",		@"TEXT"],
                                                @[@"typeName",		@"TEXT"],
                                                @[@"updateTime",	@"DATE"],//上次修改时间
                                                @[@"pictureFileName",@"TEXT"],
                                                @[@"secretMode",	@"BOOLEAN"],
                                                @[@"password",		@"TEXT"],
                                                ]];
        
        
//        [_magager insertDataToTable:@"type" Columnns:@[
//                                                       @[@"typeID",		@"0"],
//                                                       @[@"userID",		@"null"],
//                                                       @[@"typeName",	@"心情"],
//                                                       @[@"objectID",	@"null"],
//                                                       @[@"updateTime",	@"0"],//上次修改时间
//                                                       @[@"pictureFileName",@"localHost://paper1"],
//                                                       @[@"secretMode",	@"0"],
//                                                       @[@"password",	@""],
//                                                       ]];
//        
//        [_magager insertDataToTable:@"type" Columnns:@[
//                                                       @[@"typeID",		@"1"],
//                                                       @[@"userID",		@"null"],
//                                                       @[@"typeName",	@"杂记"],
//                                                       @[@"updateTime",	@"0"],//上次修改时间
//                                                       @[@"objectID",	@"null"],
//                                                       @[@"pictureFileName",@"localHost://paper2"],
//                                                       @[@"secretMode",	@"0"],
//                                                       @[@"password",	@""],
//                                                       ]];
//        [_magager insertDataToTable:@"type" Columnns:@[
//                                                       @[@"typeID",		@"2"],
//                                                       @[@"userID",		@"null"],
//                                                       @[@"objectID",	@"null"],
//                                                       @[@"updateTime",	@"0"],//上次修改时间
//                                                       @[@"typeName",	@"旅行日记"],
//                                                       @[@"pictureFileName",@"localHost://black.jpg"],
//                                                       @[@"secretMode",	@"0"],
//                                                       @[@"password",	@""],
//                                                       ]];
    }
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    
    FMResultSet * resultSet = [_magager queryDataFromTable:@"type" Columnns:@[@"*"] condition:[NSString stringWithFormat:@"userID = '%@' and pictureFileName != 'null' ORDER BY typeID",userId]];
    
    NSMutableArray * types = [NSMutableArray array];
    while ([resultSet next]) {
        BSKNoteType * type = [[BSKNoteType alloc]init];
        type.typeID = [resultSet stringForColumn:@"typeID"];
        type.userID = [resultSet stringForColumn:@"userID"];
        type.typeName = [resultSet stringForColumn:@"typeName"];
        type.pictureFileName = [resultSet stringForColumn:@"pictureFileName"];
        type.password = [resultSet stringForColumn:@"password"];
        type.secretMode = [resultSet boolForColumn:@"secretMode"];
        [types addObject:type];
    }
    _typeList = [types copy];
    [resultSet close];
    [_magager.fmDatabase close];
    [_categoryTableView reloadData];
}

-(void)initializeNotlistDataWithcondition:(NSString * )condition{
    NSString * condition_order = [NSString stringWithFormat:@"%@ ORDER BY updateTime DESC",condition];
    FMResultSet * result = [_magager queryDataFromTable:@"note"
                                               Columnns:@[
                                                          @"noteID",
                                                          @"objectID",
                                                          @"isChange",
                                                          @"updateTime",
                                                          @"userID",
                                                          @"typeID",
                                                          @"latitude",
                                                          @"longitude",
                                                          @"title",
                                                          @"weatherType",
                                                          @"date",
                                                          @"address",
                                                          @"subcontent",
                                                          @"noteFileName",]
                                              condition:condition_order];
    _noteList = [NSMutableArray array];
    while ([result next]) {
        BSKNote * bskNote = [[BSKNote alloc]init];
        bskNote.noteID = [result stringForColumn:@"noteID"];
        bskNote.objectID = [result stringForColumn:@"objectID"];
        bskNote.isChange = [result boolForColumn:@"isChange"];
        bskNote.updateTime = [result longForColumn:@"updateTime"];
        bskNote.userID = [result stringForColumn:@"userID"];
        bskNote.typeID = [result stringForColumn:@"typeID"];
        bskNote.title = [result stringForColumn:@"title"];
        bskNote.weatherType = [result intForColumn:@"weatherType"];
        bskNote.date = [result stringForColumn:@"date"];
        bskNote.address = [result stringForColumn:@"address"];
        bskNote.subcontent = [result stringForColumn:@"subcontent"];
        bskNote.noteFileName = [result stringForColumn:@"noteFileName"];
        bskNote.latitude = [result doubleForColumn:@"latitude"];
        bskNote.longitude = [result doubleForColumn:@"longitude"];
        [_noteList addObject:bskNote];
    }
    [result close];
    [_magager.fmDatabase close];
}

-(void)initializeUserinterFace{
    
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    /**
     *  侧滑菜单初始化
     */
    
    self.view.backgroundColor = [UIColor whiteColor];
    _gradientLayer =[CAGradientLayer layer];
    _gradientLayer.frame = self.view.bounds;
    _gradientLayer.startPoint = CGPointMake(0.3, 0.0);
    _gradientLayer.endPoint = CGPointMake(0.3, 1.0);
    [self.view.layer addSublayer:_gradientLayer];
    
    _menuView = [[UIView alloc]initWithFrame:CGRectMake(-ScreenWidth*0.8*0.5, 0, ScreenWidth, ScreenHeight)];
    _menuView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_menuView];
    
    _menuHeadImageView = [[UIImageView alloc]init];
    _usernameLabel = [[UILabel alloc]init];
    _refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _categoryTableView = [[UITableView alloc]init];
    
    _mapModeButtonView = [[UIView alloc]init];
    
    UIImageView * mapImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"map.png"]];
    mapImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    mapImageView.layer.shadowOffset = CGSizeMake(0, 0);
    mapImageView.layer.shadowOpacity = 1;
    mapImageView.layer.shadowRadius = 3;
    UILabel * mapModeLabel = [[UILabel alloc] init];
    mapModeLabel.font = [UIFont systemFontOfSize:17];
    mapModeLabel.layer.shadowColor = [UIColor blackColor].CGColor;
    mapModeLabel.layer.shadowOffset = CGSizeMake(0, 0);
    mapModeLabel.layer.shadowOpacity = 1;
    mapModeLabel.layer.shadowRadius = 3;
    mapModeLabel.textColor = [UIColor whiteColor];
    mapModeLabel.text = @"记忆足迹";
    [_mapModeButtonView addSubview:mapImageView];
    [_mapModeButtonView addSubview:mapModeLabel];
    
    [self.menuView addSubview:_menuHeadImageView];
    [self.menuView addSubview:_usernameLabel];
    [self.menuView addSubview:_refreshButton];
    [self.menuView addSubview:_categoryTableView];
    [self.menuView addSubview:_mapModeButtonView];
    
    /**
     *  地图模式按钮
     */
    
    _mapModeButtonView.sd_layout
    .bottomSpaceToView(self.menuView,10)
    .widthIs(100)
    .heightIs(30)
    .leftSpaceToView(self.menuView,ScreenWidth*0.8 - 120);
    _mapModeButtonView.backgroundColor = [UIColor clearColor];
    mapImageView.sd_layout
    .heightRatioToView(_mapModeButtonView,1)
    .widthEqualToHeight()
    .leftSpaceToView(_mapModeButtonView,0)
    .topSpaceToView(_mapModeButtonView,0);
    
    mapModeLabel.sd_layout
    .centerYEqualToView(mapImageView)
    .heightIs(30).widthIs(70)
    .leftSpaceToView(mapImageView,0);
    
    /**
     *  菜单用户头像
     */
    
    _menuHeadImageView.image = [UIImage imageNamed:@"login-no"];
    _menuHeadImageView.sd_layout
    .topSpaceToView(self.menuView,StatusBarHeight+NavigationBarHeight)
    .leftSpaceToView(self.menuView,10)
    .widthIs(80)
    .heightEqualToWidth();
    _menuHeadImageView.layer.cornerRadius = 40;
    _menuHeadImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    _menuHeadImageView.layer.shadowOpacity = 0.5;
    _menuHeadImageView.layer.shadowOffset = CGSizeMake(3,3);
    _menuHeadImageView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    _menuHeadImageView.layer.borderColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0].CGColor;
    _menuHeadImageView.layer.borderWidth = 1;
    _menuHeadImageView.clipsToBounds = YES;
    /**
     *  菜单用户名
     */
    _usernameLabel.sd_layout
    .leftSpaceToView(_menuHeadImageView,5)
    .centerYEqualToView(_menuHeadImageView)
    .heightIs(30)
    .widthIs(ScreenWidth*0.8-140);
    _usernameLabel.font = [UIFont systemFontOfSize:19];
    _usernameLabel.layer.shadowColor = [UIColor blackColor].CGColor;
    _usernameLabel.layer.shadowOffset = CGSizeMake(0, 0);
    _usernameLabel.layer.shadowOpacity = 1;
    _usernameLabel.layer.shadowRadius = 3;
    _usernameLabel.textColor = [UIColor whiteColor];
    /**
     *  刷新按钮
     */
    [_refreshButton setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
    _refreshButton.layer.shadowColor = [UIColor blackColor].CGColor;
    _refreshButton.layer.shadowOffset = CGSizeMake(0, 0);
    _refreshButton.layer.shadowOpacity = 1;
    _refreshButton.layer.shadowRadius = 3;
    _refreshButton.sd_layout
    .leftSpaceToView(_usernameLabel,5)
    .centerYEqualToView(_menuHeadImageView)
    .heightIs(30)
    .widthEqualToHeight();
    /**
     *  分类列表
     */
    _categoryTableView.sd_layout
    .leftSpaceToView(self.menuView,0)
    .topSpaceToView(self.menuHeadImageView,10)
    .widthIs(ScreenWidth*0.8)
    .bottomSpaceToView(self.menuView,50);
    _categoryTableView.backgroundColor = [UIColor clearColor];
    _categoryTableView.tag = 10086;
    _categoryTableView.dataSource = self;
    _categoryTableView.delegate = self;
    _categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    /**
     首页控件的初始化
     */
    self.contentView = [[UIView alloc]initWithFrame:self.view.bounds];
    self.notetableView = [[UITableView alloc]init];
    self.titleImageView = [[UIImageView alloc]init];
    self.headImageView = [[UIImageView alloc]init];
    self.lineView = [[UIView alloc]init];
    self.addNoteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.coverView = [[UIVisualEffectView alloc]initWithEffect:efect];
    UIBlurEffect * efect2 = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    self.titleView = [[UIVisualEffectView alloc]initWithEffect:efect2];
    self.catgorayLabel = [[UILabel alloc]init];
    self.searchTextField = [[UITextField alloc]init];
    self.bookModeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    /**
     *  添加控件到视图
     */
    [self.view addSubview:_contentView];
    [self.contentView addSubview:_titleImageView];
    [self.contentView addSubview:_coverView];
    [self.contentView addSubview:_lineView];
    [self.contentView addSubview:_notetableView];
    [self.contentView addSubview:_searchTextField];
    [self.contentView addSubview:_titleView];
    [self.contentView addSubview:_headImageView];
    [self.contentView addSubview:_catgorayLabel];
    [self.contentView addSubview:_addNoteButton];
    [self.contentView addSubview:_bookModeButton];
    
    /**
     *  状态栏阴影
     */
    CAGradientLayer * StatuBarGradientLayer =[CAGradientLayer layer];
    StatuBarGradientLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, StatusBarHeight);
    StatuBarGradientLayer.colors = @[(id)[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3] CGColor],(id)[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0] CGColor]];
    StatuBarGradientLayer.startPoint = CGPointMake(0, 0);
    StatuBarGradientLayer.endPoint = CGPointMake(0, 1.0);
    [self.view.layer addSublayer:StatuBarGradientLayer];
    /**
     *  内容背景视图
     */
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.contentView.layer.shadowOffset = CGSizeMake(-5, 0);
    self.contentView.layer.shadowOpacity = 0.5;
    self.contentView.layer.shadowRadius = 10;
    
    /**
     *  封面图片
     */
    
    _titleImageView.sd_layout
    .topSpaceToView(self.contentView,0)
    .leftSpaceToView(self.contentView,0)
    .rightSpaceToView(self.contentView,0)
    .bottomSpaceToView(self.contentView,0);
    _titleImageView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    
    /**
     *  用于遮挡titleImageView产生动画效果
     */
    
    _coverView.sd_layout
    .topSpaceToView(self.titleView,0)
    .widthRatioToView(self.notetableView,1)
    .bottomSpaceToView(self.contentView,0);
    _coverView.alpha = 0;
    /**
     *  日记列表
     */
    
    _notetableView.sd_layout
    .topSpaceToView(self.contentView,0)
    .bottomSpaceToView(self.contentView,0)
    .leftSpaceToView(self.contentView,0)
    .rightSpaceToView(self.contentView,0);
    _notetableView.backgroundColor = [UIColor clearColor];
    _notetableView.delegate = self;
    _notetableView.dataSource = self;
    _notetableView.tag = 10010;
    _notetableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    /**
     *  搜索框
     */
    _searchTextField.sd_layout
    .leftSpaceToView(_lineView,10)
    .rightSpaceToView(self.contentView,10)
    .topSpaceToView(self.contentView,ScreenWidth/2+10)
    .heightIs(30);
    [_searchTextField setBorderStyle:UITextBorderStyleRoundedRect];
    _searchTextField.returnKeyType = UIReturnKeySearch;
    _searchTextField.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:0.6];
    _searchTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"搜索" attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    [_searchTextField setClearButtonMode:UITextFieldViewModeAlways];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(searchTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:_searchTextField];
    _searchTextField.delegate = self;
    /**
     *  头像
     */
    _headImageView.image = [UIImage imageNamed:@"login-no"];
    _headImageView.sd_layout
    .topSpaceToView(self.contentView,ScreenWidth/2-70)
    .centerXIs(50)
    .widthIs(80)
    .heightEqualToWidth();
    _headImageView.layer.cornerRadius = 40;
    _headImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    _headImageView.layer.shadowOpacity = 0.5;
    _headImageView.layer.shadowOffset = CGSizeMake(3,3);
    _headImageView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    _headImageView.layer.borderColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0].CGColor;
    _headImageView.layer.borderWidth = 1;
    _headImageView.clipsToBounds = YES;
    /**
     *  顶部导航栏视图
     */
	
    _titleView.sd_layout
    .topSpaceToView(self.contentView,0)
    .leftSpaceToView(self.contentView,0)
    .rightSpaceToView(self.contentView,0)
    .heightIs(StatusBarHeight+NavigationBarHeight);
    _titleView.alpha = 0;
 
    /**
     *  阅读模式按钮
     */
    _bookModeButton.sd_layout
    .centerYEqualToView(_catgorayLabel)
    .centerXIs(ScreenWidth - 40)
    .widthIs(35)
    .heightEqualToWidth();
    [_bookModeButton setImage:[UIImage imageNamed:@"book"] forState:UIControlStateNormal];
	/**
	 *  分类名称
	 */
	_catgorayLabel.sd_layout
	.leftSpaceToView(_headImageView,10)
	.rightSpaceToView(_bookModeButton,5)
	.centerYEqualToView(_headImageView)
	.heightIs(30);
	_catgorayLabel.font = [UIFont systemFontOfSize:19];
	_catgorayLabel.layer.shadowColor = [UIColor blackColor].CGColor;
	_catgorayLabel.layer.shadowOffset = CGSizeMake(0, 0);
	_catgorayLabel.layer.shadowOpacity = 1;
	_catgorayLabel.layer.shadowRadius = 3;
	_catgorayLabel.textColor = [UIColor whiteColor];
	_catgorayLabel.text = @"分类名称";
    /**
     *  新建日记按钮
     */
    _addNoteButton.sd_layout
    .widthIs(50)
    .heightIs(50)
    .rightSpaceToView(self.contentView,5)
    .bottomSpaceToView(self.contentView,5);
    _addNoteButton.layer.cornerRadius = 25;
    [_addNoteButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    _addNoteButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_addNoteButton setBackgroundColor:[UIColor blueColor]];
    /**
     *  时间轴竖线
     */
    
    _lineView.sd_layout
    .topSpaceToView(_headImageView,-10)
    .bottomSpaceToView(self.contentView,0)
    .leftSpaceToView(self.contentView,55)
    .widthIs(1);
    _lineView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
	
	if (![[NSUserDefaults standardUserDefaults] objectForKey:@"firstLaunch"]) {
		_helpImageView = [[UIImageView alloc]init];
		[self.view addSubview:_helpImageView];
		_helpImageView.image = [UIImage imageNamed:@"helpimage"];
		_helpImageView.sd_layout
		.leftSpaceToView(self.view,0)
		.rightSpaceToView(self.view,0)
		.topSpaceToView(self.view,0)
		.bottomSpaceToView(self.view,0);
		
		_okButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[self.view addSubview:_okButton];
		_okButton.sd_layout
		.bottomSpaceToView(self.view,20)
		.leftSpaceToView(self.view,20)
		.heightIs(50)
		.widthIs(150);
		_okButton.backgroundColor = [UIColor colorWithRed:0.9608 green:0.3255 blue:0.7333 alpha:1.0];
		[_okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[_okButton setTitle:@"我知道了" forState:UIControlStateNormal];
		_okButton.titleLabel.font = [UIFont systemFontOfSize:30];
		_okButton.layer.cornerRadius = 10;
		[_okButton addTarget:self action:@selector(hideHelpImageAction:) forControlEvents:UIControlEventTouchUpInside];
	}
	
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"firstLaunch"]) {
//        NSArray *images = @[@"paper1", @"paper2", @"launchImage"];
//        _scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
//        _scrollView.backgroundColor = [UIColor grayColor];
//        _scrollView.contentSize = CGSizeMake(SCROOL_L * images.count, SCROOL_H);
//        _scrollView.pagingEnabled = YES;
//        _scrollView.bounces = NO;
//        _scrollView.showsHorizontalScrollIndicator = NO;
//        _scrollView.delegate = self;
//        _scrollView.contentOffset = CGPointMake(0, 0);
//        for (NSInteger index = 0; index < images.count; index++) {
//            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCROOL_L * index, 0, SCROOL_L, SCROOL_H)];
//            imageView.image = [UIImage imageNamed:images[index]];
//            [_scrollView addSubview:imageView];
//            if (index == 2) {
//                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//                button.bounds = CGRectMake(0, 0, SCROOL_L, SCROOL_H);
//                button.center = CGPointMake(SCROOL_L * (images.count - 0.5), SCROOL_H * 0.5);
//                button.titleLabel.font = [UIFont systemFontOfSize:20];
//                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//                [button addTarget:self action:@selector(leadingButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//                [_scrollView addSubview:button];
//            }
//        }
//        [self.view addSubview:_scrollView];
//        _pageControl = [[UIPageControl alloc]init];
//        _pageControl.bounds = CGRectMake(0, 0, SCROOL_L, 30);
//        _pageControl.center = CGPointMake(self.view.centerX, SCROOL_H - 50);
//        //总页数
//        _pageControl.numberOfPages = images.count;
//        //当前页
//        _pageControl.currentPage = 0;
//        //被选中时指示器的颜色
//        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
//        [self.view addSubview:_pageControl];
//    }
}


-(void)loadContent{
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    [self initializeNotlistDataWithcondition:[NSString stringWithFormat:@"typeID = '%@' and userID = '%@' and noteFileName != 'null'",_curenttype.typeID ,userId]];
    [_notetableView reloadData];
    NSLog(@"%@",_curenttype.pictureFileName);
    if ([[_curenttype.pictureFileName substringToIndex:12] isEqualToString:@"localHost://"]) {
        [BSKTheme curentTheme].themeImage = [UIImage imageNamed:[_curenttype.pictureFileName substringFromIndex:12]];
    }else{
        NSString * typeImageDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSData * imageData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",typeImageDirPath,_curenttype.pictureFileName]];
        [BSKTheme curentTheme].themeImage = [UIImage imageWithData:imageData];
    }
    _addNoteButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    _gradientLayer.colors = [BSKTheme curentTheme].menuThemeColors;
    _titleImageView.image = [BSKTheme curentTheme].themeImage;
    _catgorayLabel.text = _curenttype.typeName;
}

-(void)initializeAction{
    UITapGestureRecognizer * openMenuGesture= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openMenuAction:)];
    UITapGestureRecognizer * openMenuGesture2= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openMenuAction:)];
    [_headImageView addGestureRecognizer:openMenuGesture];
    _headImageView.userInteractionEnabled = YES;
    [_catgorayLabel addGestureRecognizer:openMenuGesture2];
    _catgorayLabel.userInteractionEnabled = YES;
    
    UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.view addGestureRecognizer:panGesture];
    
    UITapGestureRecognizer * openUserCenterGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openUserCenterAction:)];
    UITapGestureRecognizer * openUserCenterGesture2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openUserCenterAction:)];
    [_menuHeadImageView addGestureRecognizer:openUserCenterGesture];
    _menuHeadImageView.userInteractionEnabled = YES;
    [_usernameLabel addGestureRecognizer:openUserCenterGesture2];
    _usernameLabel.userInteractionEnabled = YES;
    [_addNoteButton addTarget:self action:@selector(addNewNoteAction:) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer * openMapModeGesture= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openMapModeAction:)];
    [_mapModeButtonView addGestureRecognizer:openMapModeGesture];
    [_refreshButton addTarget:self action:@selector(refreshAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bookModeButton addTarget:self action:@selector(openBookModeAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setUserInterFaceWithUpdateHeaderOrNot:(BOOL)updateHeader{
    AVUser * user =[AVUser currentUser];
    if (user!=nil) {
        _usernameLabel.text = [user objectForKey:@"nickName"];
        NSLog(@"%@",[user objectForKey:@"nickName"]);
        NSString * headerUrlString = [user objectForKey:@"userHeader"];
        if (headerUrlString && updateHeader){
            NSURL * url = [NSURL URLWithString:headerUrlString];
            [_headImageView sd_setImageWithURL:url placeholderImage:_headImageView.image completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                _menuHeadImageView.image = image;
            }];
        }
    }else{
        _headImageView.image = [UIImage imageNamed:@"login-no"];
        _menuHeadImageView.image = _headImageView.image;
        _usernameLabel.text = @"请登录";
    }
}

#pragma mark Action
-(void)openBookModeAction:(UIButton *)sender{
    if (_noteList.count>0) {
        BSKBookModeViewController * bookVC = [[BSKBookModeViewController alloc]init];
        bookVC.noteList = _noteList;
        [self.navigationController pushViewController:bookVC animated:YES];
    }
    else{
        [self MakeToast:@"还没有数据!\n快去新建一个吧（^_^）" WithTime:2];
    }
}

- (void)refreshAction:(UIButton *)sender {
	
	__weak typeof(self) weakSelf = self;
	AVUser * user =[AVUser currentUser];
	if (user==nil) {
	[self MakeToast:@"请先登录！" WithTime:2];
		return;
	}
	NSString * wifiOnly = [user objectForKey:@"wifiChoice"];
	if ([wifiOnly isEqualToString:@"yes"]) {
			AFNetworkReachabilityManager *rManger = [AFNetworkReachabilityManager sharedManager];
			[rManger startMonitoring];
			[rManger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
				if (status == 2) {
					[[BSKSyncManager shareSyncManager]startSyncWithController:weakSelf.navigationController];
				}else{
					[weakSelf MakeToast:@"您设置了仅在WiFi下同步\n当前为非WiFi状态，不能同步" WithTime:2];
				}
			}];
	}else{
		[[BSKSyncManager shareSyncManager]startSyncWithController:self.navigationController];
	}
	
}
-(void)longpressMenueAction:(UIButton *)sender{
    
    NSInteger actiontype = sender.tag/1000;
    NSInteger index = sender.tag%1000;
    BSKNote * note = _noteList[index];
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    switch (actiontype) {
        case 1:{
            BSKNoteViewController * editerVC = [[BSKNoteViewController alloc]init];
            editerVC.isNewNote = NO;
            editerVC.dbManager = _magager;
            editerVC.CurentNote = _noteList[index];
            editerVC.typelist = _typeList;
            [self.navigationController pushViewController:editerVC animated:YES];
        }
            break;
        case 2:
        {
            __weak typeof(self) weakself = self;
            
            BSKTypeSelecter * typeselecter = [[BSKTypeSelecter alloc]initWithTyps:_typeList selectedCallBack:^(NSString *typeID) {
                if( [weakself.magager updateDataToTable:@"note" Columnns:@[@[@"typeID",typeID],@[@"isChange",	[NSNumber numberWithBool:YES]]] condition:[NSString stringWithFormat:@"noteID = '%@' and userID = '%@'",note.noteID,userId]]){
                    [weakself MakeToast:@"移动成功" WithTime:1.5];
                }else{
                    [weakself MakeToast:@"移动失败" WithTime:1.5];
                }
                [weakself noteListDataBaseDidChange];
            }];
            typeselecter.titleLabel.text = @"移动到";
            [self.view addSubview:typeselecter];
            [self.view endEditing:YES];
            
            [typeselecter show];
            
            
        }
            break;
        case 3:
        {
            
            NSString * noteDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString * noteFilePath = [NSString stringWithFormat:@"%@/%@",noteDirPath,note.noteFileName];
            NSFileManager * filemanager = [NSFileManager defaultManager];
            NSError * erro = nil;
            [filemanager removeItemAtPath:noteFilePath error:&erro];
            if (erro) {
                [self MakeToast:[NSString stringWithFormat: @"删除失败:%@",erro] WithTime:1.5];
            }else{
                if( [self.magager updateDataToTable:@"note" Columnns:@[@[@"noteFileName",@"null"]] condition:[NSString stringWithFormat:@"noteID = '%@' and userID = '%@'",note.noteID,userId]]){
                    [self MakeToast:@"删除成功" WithTime:1.5];
                }else{
                    [self MakeToast:@"删除失败" WithTime:1.5];
                }
            }
            
            [self noteListDataBaseDidChange];
            
        }
            break;
            
        default:
            break;
    }
}

-(void)addNewNoteAction:(UIButton *)sender{
	if (_typeList.count == 0) {
		[self MakeToast:@"您还没有创建任何分类\n向右滑动，去创建一个吧（^_^）" WithTime:1];
		return;
	}
    BSKNoteViewController * editerVC = [[BSKNoteViewController alloc]init];
    editerVC.isNewNote = YES;
    editerVC.dbManager = _magager;
    editerVC.typelist = _typeList;
    [self.navigationController pushViewController:editerVC animated:YES];
}

-(void)openMapModeAction:(UITapGestureRecognizer *)gesture{
    BSKMapViewController * mapVC = [[BSKMapViewController alloc]init];
    mapVC.noteList = _noteList;
    mapVC.manager = _magager;
    [self.navigationController pushViewController:mapVC animated:YES];
}


-(void)openUserCenterAction:(UITapGestureRecognizer *)gesture{
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser != nil) {
        // 跳转到首页
        BSKUserCenterViewController * userCenter = [[BSKUserCenterViewController alloc]init];
        [self.navigationController pushViewController:userCenter animated:YES];
    } else {
        // 缓存用户对象为空时，打开用户登录页面
        BSKLoginViewController * loginVC = [[BSKLoginViewController alloc]init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

-(void)openMenuAction:(UITapGestureRecognizer *)gesture{
    CGRect frame = _contentView.frame;
    frame.origin.x = self.view.bounds.size.width*0.8;
    CGRect frame2 = _menuView.frame;
    frame2.origin.x = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.frame = frame;
        _headImageView.alpha = 0;
        _catgorayLabel.alpha = 0;
        _menuView.frame = frame2;
    } completion:^(BOOL finished) {
        _menuIsOpen = YES;
        _contentView.userInteractionEnabled = NO;
    }];
}


-(void)closeMenuAction:(UITapGestureRecognizer *)gesture{
    CGRect frame = _contentView.frame;
    frame.origin.x = 0;
    CGRect frame2 = _menuView.frame;
    frame2.origin.x = -ScreenWidth*0.8*0.5;
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.frame = frame;
        _headImageView.alpha = 1;
        _catgorayLabel.alpha = 1;
        _menuView.frame = frame2;
    } completion:^(BOOL finished) {
        _menuIsOpen = NO;
        _contentView.userInteractionEnabled = YES;
    }];
}

-(void)panAction:(UIPanGestureRecognizer *)gesture{
    CGPoint p = [gesture translationInView:self.view];
    CGFloat baseX = 0.0;
    if (_menuIsOpen) {
        baseX = self.view.bounds.size.width*0.8;
    }
    if (gesture.state == UIGestureRecognizerStateBegan){
        
    }
    
    if (gesture.state == UIGestureRecognizerStateChanged) {
        if (_contentView.frame.origin.x>=0&&_contentView.origin.x<=self.view.bounds.size.width*0.8) {
            CGRect contentFrame = _contentView.frame;
            contentFrame.origin.x = baseX + p.x;
            
            if (contentFrame.origin.x<0) {
                contentFrame.origin.x =0 ;
            }
            if (contentFrame.origin.x >self.view.bounds.size.width*0.8){
                contentFrame.origin.x =self.view.bounds.size.width*0.8;
            }
            _contentView.frame = contentFrame;
            CGFloat percent =_contentView.frame.origin.x/(self.view.bounds.size.width*0.8);
            
            _headImageView.alpha = 1-percent;
            _catgorayLabel.alpha = 1-percent;
            CGRect frame2 = _menuView.frame;
            frame2.origin.x = -ScreenWidth*0.8*0.5 * (1- percent);
            _menuView.frame = frame2;
        }
    }
    
    if (gesture.state == UIGestureRecognizerStateEnded) {
        if (_contentView.origin.x > self.view.bounds.size.width*0.8*0.5) {
            [self openMenuAction:nil];
        }
        else{
            [self closeMenuAction:nil];
        }
    }
};
- (void)classifyEditButtonAction:(UIButton *)sender {
    BSKClassifyManageViewController *classifyManageVC = [[BSKClassifyManageViewController alloc] init];
    [self.navigationController pushViewController:classifyManageVC animated:YES];
}
- (void)classifyAddButtonAction:(UIButton *)sender {
    BSKClassifySettingViewController *addClassifyManageVC = [[BSKClassifySettingViewController alloc] init];
    addClassifyManageVC.status = YES;
    [self.navigationController pushViewController:addClassifyManageVC animated:YES];
}
-(void)hideHelpImageAction:(UIButton * )sender{
	[[NSUserDefaults standardUserDefaults]setObject:@"notFirstLaunch" forKey:@"firstLaunch"];
	[UIView animateWithDuration:0.25 animations:^{
		_helpImageView.alpha = 0;
		_okButton.alpha = 0;
	} completion:^(BOOL finished) {
		[_helpImageView removeFromSuperview];
		[_okButton removeFromSuperview];
	}];
	
}

//- (void)leadingButtonAction:(UIButton *)sender {
//    [[ NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
//    [UIView animateWithDuration:1.5 animations:^{
//        _scrollView.alpha = 0;
//        _pageControl.currentPage = 0;
//    } completion:^(BOOL finished) {
//        [_scrollView removeFromSuperview];
//        [_pageControl removeFromSuperview];
//    }];
//}
#pragma mark UItableViewDatasource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag ==10086) {
        return _typeList.count;
    }
    return _noteList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	if (tableView.tag == 10086) {
		UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"noteCell"];
		if (!cell) {
			cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"noteCell"];
		}
		cell.backgroundColor = [UIColor clearColor];
		cell.textLabel.layer.shadowColor = [UIColor blackColor].CGColor;
		cell.textLabel.layer.shadowOffset = CGSizeMake(0, 0);
		cell.textLabel.layer.shadowOpacity = 1;
		cell.textLabel.layer.shadowRadius = 3;
		cell.textLabel.textColor = [UIColor whiteColor];
		cell.textLabel.sd_layout.leftSpaceToView(cell.textLabel.superview,ScreenWidth*0.15);
		BSKNoteType * type =_typeList[indexPath.row];
		cell.textLabel.text = type.typeName;
		cell.imageView.image = [self imageResize:[UIImage imageNamed:@"key"] ToSize:CGSizeMake(20, 20)] ;
		if (type.secretMode) {
			cell.imageView.hidden = NO;
		}else{
			cell.imageView.hidden = YES;
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		return cell;
	}
	
	__weak typeof(self) weakSelf = self;
	BSKNoteTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"noteCell"];
	if (!cell) {
		cell = [[BSKNoteTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"noteCell" longpressCallBack:^(UITableViewCell * cell){
			
			UIButton * editButton = [UIButton buttonWithType:UIButtonTypeCustom];
			UIButton * movetoButton = [UIButton buttonWithType:UIButtonTypeCustom];
			UIButton * deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
			[editButton setTitle:@"编辑" forState:UIControlStateNormal];
			[movetoButton setTitle:@"移动到" forState:UIControlStateNormal];
			[deleteButton setTitle:@"删除" forState:UIControlStateNormal];
			
			[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
			[movetoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
			[deleteButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
			
			NSInteger index = [tableView indexPathForCell:cell].row;
			editButton.tag = 1000+index;
			movetoButton.tag = 2000 + index;
			deleteButton.tag = 3000 +index;
			
			BSKMenuAlertView * menu = [[BSKMenuAlertView alloc]initWithButtons:@[editButton,movetoButton,deleteButton] buttonActionCallBack:^(UIButton *sender) {
				[self longpressMenueAction:sender];
			}];
			[weakSelf.view addSubview:menu];
			[menu show];
		}] ;
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	[cell setCelWithNote:_noteList[indexPath.row]];
	return cell;
}

#pragma mark UItableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 10086) {
        return 44;
    }
    return 150;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 10086) {
        return 0;
    }
    return ScreenWidth/2+50;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 10086) {
        return nil;
    }
    self.tableHeaderView = [[UIView alloc]init];
    _tableHeaderView.frame = CGRectMake(0, 0, tableView.bounds.size.width, [self tableView:tableView heightForHeaderInSection:section]);
    _tableHeaderView.backgroundColor = [UIColor clearColor];
    _tableHeaderView.userInteractionEnabled = NO;
    return _tableHeaderView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView.tag == 10086) {
        return 40;
    }
    return 0;
}
-(UIView * )tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (tableView.tag == 10010) {
        return nil;
    }
    UIView * footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, [self tableView:tableView heightForFooterInSection:section])];
    footerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.2];
    UIButton * addCategoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addCategoryButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addCategoryButton addTarget:self action:@selector(classifyAddButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIButton * editCategoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [editCategoryButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    [editCategoryButton addTarget:self action:@selector(classifyEditButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIView * centerView = [[UIView alloc] init];
    
    [footerView addSubview:addCategoryButton];
    [footerView addSubview:editCategoryButton];
    [footerView addSubview:centerView];
    centerView.sd_layout.widthIs(1)
    .heightIs(1)
    .centerYIs(footerView.height/2)
    .centerXIs(footerView.width/2);
    addCategoryButton.sd_layout
    .heightRatioToView(footerView,0.7)
    .widthEqualToHeight()
    .rightSpaceToView(centerView,footerView.width/6)
    .centerYEqualToView(centerView);
    editCategoryButton.sd_layout
    .heightRatioToView(footerView,0.7)
    .widthEqualToHeight()
    .leftSpaceToView(centerView,footerView.width/6)
    .centerYEqualToView(centerView);
    return footerView;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 10086) {
        BSKNoteType * type = _typeList[indexPath.row];
        [self ChangeCurentType:type];
        return;
    }
    
    BSKNoteViewController * editerVC = [[BSKNoteViewController alloc]init];
    editerVC.isNewNote = NO;
    editerVC.dbManager = _magager;
    editerVC.CurentNote = _noteList[indexPath.row];
    editerVC.typelist = _typeList;
    [self.navigationController pushViewController:editerVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 10086) {
        return;
    }
    static  NSInteger indexNumber = 0;
    if(_showCellAnimation){
        cell.transform = CGAffineTransformMakeScale(0.001, 0.001);		[UIView animateWithDuration:0.5 delay:((indexPath.row-indexNumber)*0.07) usingSpringWithDamping:0.7 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            cell.transform = CGAffineTransformMakeScale(1, 1);
        } completion:nil];
    }else{
        NSIndexPath * firstIndexPath = [tableView indexPathForCell:[tableView.visibleCells firstObject]];
        indexNumber = firstIndexPath.row;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (_searchTextField.isFirstResponder) {
        [self.searchTextField endEditing:YES];
    }
    
    _showCellAnimation = NO;
    CGFloat y = _notetableView.contentOffset.y;
    if (y < 0) {
        y=0;
    }
    CGFloat alpha = y/(ScreenWidth/2-StatusBarHeight-NavigationBarHeight);
    if (alpha < 0) {
        alpha = 0;
    }
    if (alpha > 1) {
        alpha = 1;
    }
    
    _titleView.alpha =alpha;
    CGFloat top = ScreenWidth/2-_headImageView.height+10-y;
    if (top < StatusBarHeight) {
        top = StatusBarHeight;
    }
    _headImageView.sd_layout
    .widthIs(80*(1-0.3*alpha))
    .topSpaceToView(self.contentView,top);
    _headImageView.layer.cornerRadius = 40*(1-0.3*alpha);
    CGFloat coverViewY = ScreenWidth/2 -y;
    CGFloat titleViewY = -(StatusBarHeight+NavigationBarHeight)*(1-alpha);
    CGFloat titleImageViewY = 0-y*0.5;
    if (titleImageViewY <-(StatusBarHeight+NavigationBarHeight) ) {
        titleImageViewY = -(StatusBarHeight+NavigationBarHeight) ;
    }
    if (coverViewY < StatusBarHeight+NavigationBarHeight) {
        coverViewY = StatusBarHeight +NavigationBarHeight;
    }
    _coverView.alpha = alpha;
    _searchTextField.sd_layout.topSpaceToView(self.contentView,ScreenWidth*0.5 +10 -y);
    _titleView.sd_layout.topSpaceToView(self.contentView,titleViewY);
    _titleImageView.sd_layout.topSpaceToView(self.contentView,titleImageViewY);
    for(UIView *  v in self.contentView.subviews){
        [v updateLayout];
    }
    
//    if (scrollView == _scrollView) {
//        _pageControl.currentPage = round(scrollView.contentOffset.x/SCROOL_L);
//    }
}
#pragma mark searchTextFieldDidChange


-(void)searchTextFieldDidChange:(NSNotification *)notify{
    
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    [self initializeNotlistDataWithcondition:[NSString stringWithFormat:@"typeID = '%@' and userID = '%@' and subcontent like '%%%@%%' ",_curenttype.typeID ,userId, _searchTextField.text]];
    [_notetableView reloadData];
}

#pragma mark toolFunctions

-(void)ChangeCurentType:(BSKNoteType *)type{
    
    __weak typeof(self) weakSelf = self;
    if (type.secretMode) {
        BSKTypePasswdAlertView * alertView = [[BSKTypePasswdAlertView alloc]initWithNoteType:type successCallBack:^(BOOL isSuccess) {
            if(isSuccess){
                [weakSelf closeMenuAction:nil];
                _curenttype = type;
                [weakSelf loadContent];
            }
            else{
                [weakSelf MakeToast:@"密码错误！" WithTime:3];
            }
        }];
        [self.view addSubview:alertView];
        [alertView show];
        
    }
    else{
        [self closeMenuAction:nil];
        _curenttype = type;
        [self loadContent];
    }
}

-(UIView *)getscreenSnapshotWithoutMenuHeadImageView{
    self.menuHeadImageView.hidden = YES;
    [self.view setNeedsDisplay];
    UIView* screenSnapshot = [self.view snapshotViewAfterScreenUpdates:YES];
    self.menuHeadImageView.hidden =  NO;
    return screenSnapshot;
}
#pragma mark UINavigationControllerDelegate

-(id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    if (([toVC isKindOfClass:[BSKLoginViewController class]]  || [toVC isKindOfClass:[BSKUserCenterViewController class]]) && [fromVC isKindOfClass:[BSKHomeViewController class]]&& operation == UINavigationControllerOperationPush ) {
        BSKHomeVCToLoginVCanimation * animation = [[BSKHomeVCToLoginVCanimation alloc]init];
        return animation;
    }else if (([toVC isKindOfClass:[BSKNoteViewController class]]&&[fromVC isKindOfClass:[BSKHomeViewController class]])||[toVC isKindOfClass:[BSKHomeViewController class]]) {
        BSKAddButtonAnimation * AddAnimation = [[BSKAddButtonAnimation alloc]init];
        if (operation == UINavigationControllerOperationPush) {
            AddAnimation.isPush = YES;
        }
        else{
            AddAnimation.isPush = NO;
        }
        return AddAnimation;
    }
    
    return nil;
}

- (UIImage*)imageResize:(UIImage*)image ToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width,size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - UIScrollViewDelegate
@end
